<template>
  <div class="referral-page">
      <div class="page-container">
        <div class="page-header">
          <h1 class="page-title">{{ $t('pages.referral.title') }}</h1>
          <p class="page-subtitle">{{ $t('pages.referral.subtitle') }}</p>
        </div>
        
        <div class="content-grid">
          <!-- 推荐人信息卡片 -->
          <div class="referral-info-card">
            <div class="card-header">
              <h3>{{ $t('pages.referral.referralInfo') }}</h3>
            </div>
            <div class="referral-code-section">
              <div class="code-display">
                <label>{{ $t('pages.referral.referralCode') }}</label>
                <div class="code-value">
                  <span>{{ referralInfo?.referralCode }}</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="copyReferralCode"
                    :loading="copyingCode"
                  >
                    {{ $t('pages.referral.copyLink') }}
                  </el-button>
                </div>
              </div>
              <div class="link-display">
                <label>{{ $t('pages.referral.referralLink') }}</label>
                <div class="link-value">
                  <span>{{ referralInfo?.referralLink }}</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="copyReferralLink"
                    :loading="copyingLink"
                  >
                    {{ $t('pages.referral.copyLink') }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 推荐人收益卡片（显示NEAR数量） -->
          <div class="earnings-card">
            <div class="card-header">
              <h3>{{ $t('pages.referral.referralEarnings') }}</h3>
              <el-button
                type="primary"
                size="small"
                @click="showWithdrawDialog"
              >
                {{ $t('pages.referral.withdrawButton') }}
              </el-button>
            </div>
            <div class="earnings-grid">
              <div class="earning-item">
                <div class="earning-label">{{ $t('pages.referral.accumulatedEarnings') }}</div>
                <div class="earning-value">{{ formatNear(referralEarnings?.stakingEarnings.accumulated || 0) }} NEAR</div>
              </div>
              <div class="earning-item">
                <div class="earning-label">{{ $t('pages.referral.todayEarnings') }}</div>
                <div class="earning-value">{{ formatNear(referralEarnings?.stakingEarnings.today || 0) }} NEAR</div>
              </div>
              <div class="earning-item total">
                <div class="earning-label">{{ $t('pages.referral.totalEarnings') }}</div>
                <div class="earning-value">{{ formatNear(referralEarnings?.stakingEarnings.total || 0) }} NEAR</div>
              </div>
            </div>
          </div>

          <!-- 推荐人列表卡片 -->
          <div class="referral-list-card">
            <div class="card-header">
              <h3>{{ $t('pages.referral.referralList') }}</h3>
              <div class="user-count">{{ totalReferrals }} {{ $t('pages.referral.people') }}</div>
            </div>

            <!-- 搜索框 -->
            <div class="search-section">
              <el-input
                v-model="searchQuery"
                :placeholder="$t('pages.referral.searchPlaceholder')"
                size="large"
                clearable
                @input="handleSearch"
                @clear="handleSearch"
              >
                <template #prefix>
                  <Icon icon="mdi:magnify" width="16" height="16" />
                </template>
              </el-input>
            </div>

            <!-- 用户列表 -->
            <div class="users-list" v-loading="listLoading">
              <div v-if="filteredUsers.length === 0" class="no-users">
                <Icon icon="mdi:account-group-outline" width="48" height="48" />
                <p>{{ $t('pages.referral.noReferrals') }}</p>
              </div>
              <div v-else class="users-table">
                <div class="table-header">
                  <div class="col-id">{{ $t('pages.referral.userId') }}</div>
                  <div class="col-name">{{ $t('pages.referral.userName') }}</div>
                  <div class="col-idnumber">{{ $t('pages.referral.idNumber') }}</div>
                  <div class="col-date">{{ $t('pages.referral.registrationDate') }}</div>
                </div>
                <div class="table-body">
                  <div
                    v-for="user in filteredUsers"
                    :key="user.id"
                    class="table-row"
                  >
                    <div class="col-id">{{ user.id }}</div>
                    <div class="col-name">{{ user.name }}</div>
                    <div class="col-idnumber">{{ user.idNumber }}</div>
                    <div class="col-date">{{ formatDate(user.registrationDate) }}</div>
                  </div>
                </div>
              </div>

              <div
                v-if="!isSearchMode && pagination.total > 0"
                class="pagination-container"
              >
                <el-pagination
                  background
                  layout="total, prev, pager, next, sizes"
                  :current-page="pagination.page"
                  :page-size="pagination.limit"
                  :page-sizes="[10, 20, 50]"
                  :total="pagination.total"
                  @current-change="handlePageChange"
                  @size-change="handleSizeChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 提现弹窗 -->
      <el-dialog
        v-model="withdrawDialogVisible"
        title="추천 수익 출금 신청"
        width="550px"
        :close-on-click-modal="false"
      >
        <div v-if="loadingPrice" class="loading-price">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>가격 정보를 불러오는 중...</span>
        </div>

        <el-form
          v-else
          ref="withdrawFormRef"
          :model="withdrawForm"
          :rules="withdrawRules"
          label-width="120px"
        >
          <!-- 价格信息 -->
          <div class="price-info-box">
            <div class="price-info-item">
              <span class="label">🔒 현재 NEAR 가격</span>
              <span class="value">₩{{ formatKrw(lockedNearPrice) }}</span>
            </div>
            <div class="price-info-item">
              <span class="label">💰 최대 출금 가능</span>
              <span class="value highlight">₩{{ formatKrw(maxWithdrawKrw) }}</span>
            </div>
            <div class="price-lock-notice">
              ✅ 가격이 고정되었습니다. 출금 신청 중에도 금액이 변동되지 않습니다.
            </div>
          </div>

          <el-form-item label="출금 금액" prop="amountKrw">
            <el-input
              v-model.number="withdrawForm.amountKrw"
              type="number"
              :max="maxWithdrawKrw"
              placeholder="출금할 금액을 입력하세요 (KRW)"
            >
              <template #suffix>원</template>
            </el-input>
            <div class="form-hint">최소 출금 금액은 10,000원 입니다</div>
          </el-form-item>

          <!-- 换算详情 -->
          <div v-if="withdrawForm.amountKrw && withdrawForm.amountKrw >= 10000" class="conversion-details">
            <div class="detail-row">
              <span class="label">출금 금액</span>
              <span class="value">₩{{ formatKrw(withdrawForm.amountKrw) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">차감될 NEAR</span>
              <span class="value">{{ formatNear(withdrawForm.amountKrw / lockedNearPrice) }} NEAR</span>
            </div>
            <div class="detail-row">
              <span class="label">수수료</span>
              <span class="value free">₩0 (무료)</span>
            </div>
            <div class="detail-row total">
              <span class="label">실제 입금 예정</span>
              <span class="value">₩{{ formatKrw(withdrawForm.amountKrw) }}</span>
            </div>
          </div>

          <el-form-item label="사용 가능 NEAR">
            <div class="available-amount">
              {{ formatNear(referralEarnings?.stakingEarnings.total || 0) }} NEAR
            </div>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="withdrawDialogVisible = false">취소</el-button>
            <el-button
              type="primary"
              :loading="withdrawSubmitting"
              :disabled="loadingPrice"
              @click="submitWithdraw"
            >
              출금 신청
            </el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { Icon } from '@iconify/vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import {
  referralApiService,
  formatDate,
  type ReferredUser,
  type ReferralInfo,
  type ReferralEarningsData
} from '@/services/referralApi'
import { marketApiService, type NearPriceData } from '@/services/marketApi'

const { t } = useI18n()

// NEAR数量格式化函数
const formatNear = (value: number): string => {
  return Number(value).toLocaleString('en-US', {
    minimumFractionDigits: 4,
    maximumFractionDigits: 4
  })
}

// KRW格式化函数
const formatKrw = (krwAmount: number): string => {
  return Math.floor(krwAmount).toLocaleString('ko-KR')
}

// 响应式数据
const referralInfo = ref<ReferralInfo | null>(null)
const referralEarnings = ref<ReferralEarningsData | null>(null)
const isLoading = ref(false)
const copyingCode = ref(false)
const copyingLink = ref(false)
const searchQuery = ref('')
const searchLoading = ref(false)
const usersLoading = ref(false)
const users = ref<ReferredUser[]>([])
const searchResults = ref<ReferredUser[]>([])
const isSearchMode = ref(false)
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})
const filteredUsers = computed(() => (isSearchMode.value ? searchResults.value : users.value))
const listLoading = computed(() => (isSearchMode.value ? searchLoading.value : usersLoading.value))
const totalReferrals = computed(() => pagination.total || referralInfo.value?.totalReferredCount || 0)

// 提现相关
const withdrawDialogVisible = ref(false)
const withdrawSubmitting = ref(false)
const withdrawFormRef = ref<FormInstance>()
const withdrawForm = reactive({
  amountKrw: null as number | null
})

// 价格锁定相关
const lockedNearPrice = ref<number>(0) // 锁定的NEAR价格
const maxWithdrawKrw = ref<number>(0) // 最大可提现KRW金额
const loadingPrice = ref(false) // 加载价格状态

// 表单验证规则
const withdrawRules: FormRules = {
  amountKrw: [
    { required: true, message: '출금 금액을 입력해 주세요', trigger: 'blur' },
    { type: 'number', message: '숫자로 입력해 주세요', trigger: 'blur' },
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value < 10000) {
          callback(new Error('최소 출금 금액은 10,000원 입니다'))
        } else if (value > maxWithdrawKrw.value) {
          callback(new Error(`사용 가능한 금액을 초과했습니다 (최대: ${formatKrw(maxWithdrawKrw.value)}원)`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化数据
onMounted(async () => {
  await loadReferralData()
})

// 加载推荐人数据
const loadReferralData = async () => {
  try {
    isLoading.value = true
    const [infoData, earningsData] = await Promise.all([
      referralApiService.getReferralInfo(),
      referralApiService.getReferralEarnings()
    ])

    referralInfo.value = infoData
    referralEarnings.value = earningsData
    await loadReferralUsers()
  } catch (error) {
    console.error('추천 데이터 로드 실패:', error)
    ElMessage.error('추천 데이터를 불러오지 못했습니다')
  } finally {
    isLoading.value = false
  }
}

// 加载推荐用户列表（分页）
const loadReferralUsers = async (page = pagination.page, limit = pagination.limit) => {
  try {
    usersLoading.value = true
    const usersData = await referralApiService.getReferredUsers(page, limit)
    users.value = usersData.users
    pagination.page = usersData.pagination.page
    pagination.limit = usersData.pagination.limit
    pagination.total = usersData.pagination.total
  } catch (error) {
    console.error('추천 사용자 목록 로드 실패:', error)
    ElMessage.error('추천 사용자 목록을 불러오지 못했습니다')
  } finally {
    usersLoading.value = false
  }
}

// 复制推荐代码
const copyReferralCode = async () => {
  if (!referralInfo.value?.referralCode) return

  try {
    copyingCode.value = true
    const success = await referralApiService.copyToClipboard(referralInfo.value.referralCode)
    if (success) {
      ElMessage.success(t('pages.referral.linkCopied'))
    } else {
      ElMessage.error('복사에 실패했습니다')
    }
  } catch (error) {
    console.error('추천 코드 복사 실패:', error)
    ElMessage.error('복사에 실패했습니다')
  } finally {
    copyingCode.value = false
  }
}

// 复制推荐链接
const copyReferralLink = async () => {
  if (!referralInfo.value?.referralLink) return

  try {
    copyingLink.value = true
    const success = await referralApiService.copyToClipboard(referralInfo.value.referralLink)
    if (success) {
      ElMessage.success(t('pages.referral.linkCopied'))
    } else {
      ElMessage.error('복사에 실패했습니다')
    }
  } catch (error) {
    console.error('추천 링크 복사 실패:', error)
    ElMessage.error('복사에 실패했습니다')
  } finally {
    copyingLink.value = false
  }
}

// 处理搜索
const handleSearch = async () => {
  const keyword = searchQuery.value.trim()
  if (!keyword) {
    isSearchMode.value = false
    searchResults.value = []
    return
  }

  try {
    searchLoading.value = true
    const result = await referralApiService.searchReferredUsers(keyword)
    searchResults.value = result
    isSearchMode.value = true
  } catch (error) {
    console.error('검색 실패:', error)
    ElMessage.error('검색에 실패했습니다')
  } finally {
    searchLoading.value = false
  }
}

// 分页交互
const handlePageChange = async (page: number) => {
  if (isSearchMode.value) return
  pagination.page = page
  await loadReferralUsers(page, pagination.limit)
}

const handleSizeChange = async (size: number) => {
  if (isSearchMode.value) return
  pagination.limit = size
  pagination.page = 1
  await loadReferralUsers(1, size)
}

// 显示提现弹窗（锁定价格）
const showWithdrawDialog = async () => {
  if (!referralEarnings.value?.stakingEarnings.total || referralEarnings.value.stakingEarnings.total === 0) {
    ElMessage.warning('출금 가능한 수익이 없습니다')
    return
  }

  try {
    loadingPrice.value = true

    // 获取并锁定NEAR价格
    const priceData = await marketApiService.getNearPrice()
    lockedNearPrice.value = priceData.price

    // 计算最大可提现KRW金额（基于锁定价格）
    const availableNear = referralEarnings.value.stakingEarnings.total
    maxWithdrawKrw.value = Math.floor(availableNear * lockedNearPrice.value)

    // 重置表单
    withdrawForm.amountKrw = null

    // 显示对话框
    withdrawDialogVisible.value = true

    console.log(`价格已锁定: ₩${lockedNearPrice.value.toFixed(2)}, 最大可提现: ₩${maxWithdrawKrw.value.toLocaleString('ko-KR')}`)
  } catch (error) {
    console.error('가격 조회 실패:', error)
    ElMessage.error('가격 정보를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요.')
  } finally {
    loadingPrice.value = false
  }
}

// 提交提现申请
const submitWithdraw = async () => {
  if (!withdrawFormRef.value) return

  try {
    await withdrawFormRef.value.validate()

    if (!withdrawForm.amountKrw) {
      ElMessage.error('출금 금액을 입력해 주세요')
      return
    }

    withdrawSubmitting.value = true
    await referralApiService.submitWithdrawRequest(withdrawForm.amountKrw)

    ElMessage.success('출금 신청이 접수되었습니다. 관리자 검토를 기다려 주세요.')
    withdrawDialogVisible.value = false

    // 重新加载数据
    await loadReferralData()
  } catch (error: any) {
    console.error('출금 신청 실패:', error)
    ElMessage.error(error.message || '출금 신청에 실패했습니다')
  } finally {
    withdrawSubmitting.value = false
  }
}
</script>

<style scoped lang="scss">
.referral-page {
  padding: 32px 0;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.page-header {
  text-align: center;
  margin-bottom: 48px;
  
  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    color: #1a202c;
    margin-bottom: 12px;
  }
  
  .page-subtitle {
    font-size: 1.125rem;
    color: #64748b;
    max-width: 600px;
    margin: 0 auto;
  }
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  max-width: 1000px;
  margin: 0 auto;
}

// 通用卡片样式
.referral-info-card,
.earnings-card,
.referral-list-card {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h3 {
      font-size: 1.25rem;
      font-weight: 600;
      color: #1a202c;
      margin: 0;
    }

    .user-count {
      font-size: 0.875rem;
      color: #7c3aed;
      font-weight: 600;
    }
  }
}

// 推荐人信息卡片
.referral-info-card {
  .referral-code-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .code-display, .link-display {
    label {
      display: block;
      font-size: 0.875rem;
      font-weight: 600;
      color: #374151;
      margin-bottom: 8px;
    }
    
    .code-value, .link-value {
      display: flex;
      align-items: center;
      gap: 12px;
      
      span {
        flex: 1;
        padding: 12px 16px;
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        font-family: monospace;
        font-size: 0.875rem;
        color: #1a202c;
        word-break: break-all;
      }
      
      .el-button {
        flex-shrink: 0;
      }
    }
  }
}

// 收益卡片
.earnings-card {
  .earnings-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;

    .earning-item {
      text-align: center;
      padding: 20px;
      background: #f8fafc;
      border-radius: 12px;

      .earning-label {
        font-size: 0.875rem;
        color: #64748b;
        margin-bottom: 8px;
      }

      .earning-value {
        font-size: 1.125rem;
        font-weight: 600;
        color: #1a202c;
      }

      &.total {
        grid-column: 1 / -1;
        background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
        color: white;

        .earning-label,
        .earning-value {
          color: white;
        }

        .earning-value {
          font-size: 1.5rem;
        }
      }
    }
  }
}

// 推荐人列表卡片
.referral-list-card {
  grid-column: 1 / -1;
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h3 {
      font-size: 1.25rem;
      font-weight: 600;
      color: #1a202c;
      margin: 0;
    }

    .user-count {
      font-size: 0.875rem;
      color: #7c3aed;
      font-weight: 600;
    }
  }

  .search-section {
    margin-bottom: 24px;
  }

  .users-list {
    min-height: 200px;
  }

  .pagination-container {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
  }

  .no-users {
    text-align: center;
    padding: 60px 20px;
    color: #9ca3af;

    svg {
      margin-bottom: 16px;
    }

    p {
      margin: 0;
      font-size: 1rem;
    }
  }

  .users-table {
    .table-header,
    .table-row {
      display: grid;
      grid-template-columns: 0.8fr 1fr 1.2fr 1fr;
      gap: 16px;
      padding: 16px 0;
      align-items: center;
    }

    .table-header {
      border-bottom: 2px solid #e2e8f0;
      font-weight: 600;
      color: #374151;
      font-size: 0.875rem;
    }

    .table-row {
      border-bottom: 1px solid #f1f5f9;
      transition: background 0.2s ease;

      &:hover {
        background: #f8fafc;
      }

      &:last-child {
        border-bottom: none;
      }
    }

    .col-id {
      font-family: monospace;
      font-size: 0.875rem;
      color: #7c3aed;
    }

    .col-name {
      font-weight: 500;
      color: #1a202c;
    }

    .col-idnumber {
      font-family: monospace;
      font-size: 0.875rem;
      color: #1a202c;
    }

    .col-date {
      font-size: 0.875rem;
      color: #64748b;
    }
  }
}

// 提现弹窗样式
.loading-price {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px 20px;
  font-size: 1rem;
  color: #64748b;
}

.price-info-box {
  background: linear-gradient(135deg, #f8fafc 0%, #e0e7ff 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  border: 1px solid #e2e8f0;

  .price-info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .label {
      font-size: 0.875rem;
      color: #475569;
      font-weight: 500;
    }

    .value {
      font-size: 1rem;
      font-weight: 600;
      color: #1e293b;

      &.highlight {
        color: #7c3aed;
        font-size: 1.125rem;
      }
    }
  }

  .price-lock-notice {
    margin-top: 12px;
    padding: 10px 12px;
    background: white;
    border-radius: 8px;
    font-size: 0.8125rem;
    color: #059669;
    line-height: 1.5;
    border: 1px solid #d1fae5;
  }
}

.conversion-details {
  background: #f8fafc;
  border-radius: 12px;
  padding: 16px;
  margin: 16px 0;
  border: 1px solid #e2e8f0;

  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #e2e8f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 0.875rem;
      color: #64748b;
    }

    .value {
      font-size: 0.9375rem;
      font-weight: 600;
      color: #1e293b;

      &.free {
        color: #059669;
      }
    }

    &.total {
      margin-top: 8px;
      padding-top: 12px;
      border-top: 2px solid #cbd5e1;

      .label {
        font-weight: 600;
        color: #1e293b;
        font-size: 0.9375rem;
      }

      .value {
        font-size: 1.125rem;
        color: #7c3aed;
      }
    }
  }
}

.form-hint {
  margin-top: 8px;
  font-size: 0.875rem;
  color: #ef4444;
}

.available-amount {
  font-size: 1.125rem;
  font-weight: 600;
  color: #7c3aed;

  .krw-equivalent {
    margin-left: 8px;
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 400;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .page-container {
    padding: 0 16px;
  }

  .page-header {
    .page-title {
      font-size: 2rem;
    }
  }

  .content-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .referral-info-card,
  .earnings-card,
  .referral-list-card {
    padding: 24px;
  }

  .earnings-grid {
    grid-template-columns: 1fr !important;

    .earning-item.total {
      grid-column: 1 / -1 !important;
    }
  }

  .code-value, .link-value {
    flex-direction: column;
    align-items: stretch;

    .el-button {
      width: 100%;
    }
  }

  .users-table {
    .table-header,
    .table-row {
      grid-template-columns: 1fr;
      gap: 8px;
      padding: 12px 0;
    }

    .table-row {
      background: #f8fafc;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 8px;
      border: none;

      &:hover {
        background: #f1f5f9;
      }
    }

    .table-header {
      display: none;
    }

    .col-id::before {
      content: 'ID: ';
      font-weight: 600;
      color: #374151;
    }

    .col-name::before {
      content: '이름: ';
      font-weight: 600;
      color: #374151;
    }

    .col-idnumber::before {
      content: '아이디: ';
      font-weight: 600;
      color: #374151;
    }

    .col-date::before {
      content: '등록일: ';
      font-weight: 600;
      color: #374151;
    }
  }
}
</style>
